<template>
  <q-page class="wait-page">
    <!-- <BackHeader :noBack="true" v-if="!isApp && !useWxHook().isAnyirongMini()" title="" fixed /> -->
    <section class="wait-page-body">
      <div class="body-img">
        <img src="~/assets/images/waitpage/loading.png" alt="" class="body-img-scan">
        <img src="~/assets/images/waitpage/dp.png" alt="" class="body-img-dp">
      </div>
      <div class="wait-page-text">
        资质审核中…
        <div class="wait-page-tips">请耐心等待</div>
      </div>
      <div class="wait-page-line">
        <div class="un-active-line line-style"></div>
        <div :style="{ width: `${step / 5 * 100}%` }" class="active-line line-style"></div>
        <div :style="{ left: `calc(${step / 5 * 100}% - 34px)` }" class="line-block">{{ (step / 5 * 100).toFixed(0) }}%
        </div>
      </div>
      <div class="wait-page-detail">
        <div class="detail-item" v-for="(item, index) in textList" v-show="item.status != TextStatus.UnActive" :key="index">
          <img :class="[item.status == TextStatus.Wait ? 'wait-img' : '']" style="width: 16px; height: 16px;margin-right: 12px;" :src="imgMap[item.status].img" alt="">
          <div :style="{ color: imgMap[item.status].color }"
            style="font-weight: 600; font-size: 14px;line-height: 20px;">{{ item.text }}</div>
        </div>
      </div>
      <BackInfoDialog ref="BackInfoDialogRef" @next="backNextProd" />
      <ProdJumpDialog ref="ProdJumpDialogRef" />
      <UnionDialog ref="UnionDialogRef" @confirm="unionConfirm" @close="backNextProd"/>
      <!-- <ContactDialog /> -->
    </section>
  </q-page>
</template>

<script setup lang="ts">
import ContactDialog from 'src/components/ContactDialog.vue';
import { againMatchMerchantApi, getApiBOrderListApi } from 'src/api/merchant';
import { useAppStore } from 'src/stores/app-store';
import { useMechanismStore } from 'src/stores/mechanism-store';
import { MatchResult, MatchResultOrderItemList } from 'src/types/matchResult';
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useWxHook, } from 'src/hooks/wx_hooks';
import { gotoProd, ProdItem, ResType } from '../prodList/prodList';
import { getOptimalProductApi } from 'src/api/prod';
import BackInfoDialog from 'src/components/BackInfoDialog.vue';
import { BackInfoDialogInstance } from 'src/components/BackInfoDialog';
import ProdJumpDialog from 'src/components/ProdJumpDialog.vue';
import { ProdJumpDialogInstance } from 'src/components/ProdJump';
import activeImg from 'src/assets/images/waitpage/active.png'
import unActiveImg from 'src/assets/images/waitpage/un-active.png'
import waitImg from 'src/assets/images/waitpage/wait.png'
import UnionDialog from 'src/components/unionDialog/UnionDialog.vue';
import { UnionDialogInstance } from 'src/components/unionDialog/UnionDialog';
import { APIBItem } from 'src/types/apib';
const router = useRouter();
const route = useRoute();
enum TextStatus {
  Active,
  UnActive,
  Wait
}
const imgMap = {
  [TextStatus.Active]: {
    img: activeImg,
    color: '#1277FF',
  },
  [TextStatus.UnActive]: {
    img: unActiveImg,
    color: '#1277FF',
  },
  [TextStatus.Wait]: {
    img: waitImg,
    color: '#666666',
  }
}
const textList = ref([
  { text: '申请资料评估', status: TextStatus.Wait },
  { text: '借款风险评估', status: TextStatus.UnActive },
  { text: '机构匹配中…', status: TextStatus.UnActive },
])
const appStore = useAppStore();
const isApp = route.query.isApp as string;
enum DataType {
  MatchData,
  HalfMatchData,
  ProdData,
  FailData,
  ShopData
}
const BackInfoDialogRef = ref<BackInfoDialogInstance>();
const ProdJumpDialogRef = ref<ProdJumpDialogInstance>();
const UnionDialogRef = ref<UnionDialogInstance>();
const step = ref(1);
watch(() => step.value, () => {
  if (step.value == 2) {
    textList.value[0].status = TextStatus.Active
    textList.value[1].status = TextStatus.Wait
  }
  if (step.value == 4) {
    textList.value[1].status = TextStatus.Active
    textList.value[2].status = TextStatus.Wait
  }
  if (step.value == 5) {
    textList.value[2].status = TextStatus.Active
  }
})
const unionConfirm = (item: ProdItem) => {
  gotoProd(item, '', ProdJumpDialogRef.value)
}
const stepRun = (initDataTask?: ReturnType<typeof initData>) => {
  initDataTask ??= initData();
  const time = Math.random() * 1401 + 800;
  setTimeout(async () => {
    if (step.value === 4) {
      try {
        await initDataTask;
      } catch (error) { }
    }
    step.value++;
    if (step.value < 5) {
      stepRun(initDataTask);
    } else {
      setTimeout(() => {
        initDataTask
          .then((res) => {
            
            if (res.type === DataType.ShopData){
              return useWxHook().gotoEvaluteFaill(route);
            }
            if (res.type === DataType.MatchData) {
              return router.push({ path: '/mechanism', query: route.query });
            }
            if (res.type === DataType.HalfMatchData) {
              return useWxHook().gotoEvaluteSuccess(route);
              // return router.push({ path: '/mechanism', query: {...route.query, isHalf: 1} });
            }
            if (res.type === DataType.ProdData) {
              if(res.prod?.unionFlag){
                UnionDialogRef.value?.show(res.prod);
                return
              }else{
                return gotoProd(res.prod!, '', ProdJumpDialogRef.value)
              }
            }
            useWxHook().gotoEvaluteFaill(route);
          })
          .catch(() => {
            useWxHook().gotoEvaluteFaill(route);
          });
      }, 400);
    }
  }, time);
};
const initHalfMatchData = async () => {
  const res = await getApiBOrderListApi<{ dataList: APIBItem[] }>({});
  if(res.data?.dataList.length > 0){
    useMechanismStore().setHalfMatchData(res.data?.dataList);
    return {
      halfMatchSuccess: true,
      item: res.data?.dataList[0]
    }
  }
  return {
    halfMatchSuccess: false,
  }
}
const initMatchData = async () => {
  const res = await againMatchMerchantApi<MatchResult>();
  
  if(res.dataList.length > 0 && res.dataList[0].matchSuccess){
    const payload: MatchResult = {
      matchSuccess: true,
      orderId: res.dataList[0].orderId,
      orderProtocolUrl: res.dataList[0].orderProtocolUrl,
      orderItemList: res.dataList.map((item) => {
        return item.orderItemList[0]
      })
    }
    console.log(payload)
    useMechanismStore().setMatchData(payload);
    return payload;
  }
  return {
    matchSuccess: false,
    orderItemList: []
  }
};


const initData = async () => {
  const { pageType } = useAppStore()
  const { isAnyirongMini } = useWxHook();
  if (pageType == 'auth') {
    return { type: DataType.FailData }
  }
  const res = await initMatchData()
  if (res.matchSuccess && res.orderItemList?.length) {
    return { type: DataType.MatchData, matchData: res }
  }
  if (isAnyirongMini()) return { type: DataType.FailData }
  const resHalf = await initHalfMatchData()
  if (resHalf.halfMatchSuccess) {
    return { type: DataType.HalfMatchData, matchData: resHalf }
  }
  if (pageType == 'auth_list') {
    const isOnceShop = sessionStorage.getItem('isOnceShop');
    console.log(isOnceShop != '1', '--------')
    const prodListRes = await getOptimalProductApi<ResType>({ sceneId: 4 })
    const prod = prodListRes.data?.dataList?.[0]
    sessionStorage.setItem("jumpProdImg", prod?.productLogo)
    sessionStorage.setItem("jumpProdName", prod?.productName)
    if (!prod) return { type: DataType.FailData }
    return { type: DataType.ProdData, prod }
    // if(isOnceShop != '1'){
    //   sessionStorage.setItem('isOnceShop', '1');
    //   return { type: DataType.ShopData }
    // }else{
    //   const prodListRes = await getOptimalProductApi<ResType>({ sceneId: 4 })
    //   const prod = prodListRes.data?.dataList?.[0]
    //   sessionStorage.setItem("jumpProdImg", prod?.productLogo)
    //   sessionStorage.setItem("jumpProdName", prod?.productName)
    //   if (!prod) return { type: DataType.FailData }
    //   return { type: DataType.ProdData, prod }
    // }
  }
  // if (pageType == 'auth_match') {
  //   const prodListRes = await getOptimalProductApi<ResType>({ sceneId: 4 })
  //   const prod = prodListRes.data?.dataList?.[0]
  //   sessionStorage.setItem("jumpProdImg", prod?.productLogo)
  //   sessionStorage.setItem("jumpProdName", prod?.productName)
  //   if (!prod) return { type: DataType.FailData }
  //   return { type: DataType.ProdData, prod }
  // }
  // if (pageType == 'auth_over') {
  //   return { type: DataType.ShopData }
  // }
  return { type: DataType.FailData }
};


const popstateHandler = (e: PopStateEvent) => {
  // BackInfoDialogRef.value?.show();
  setTimeout(() => {
    window.history.pushState({ waitPage: true }, 'waitPage', window.location.href);
  });
};
const backNextProd = () => {
  step.value = 1
  textList.value = [
    { text: '申请资料评估', status: TextStatus.Wait },
    { text: '借款风险评估', status: TextStatus.UnActive },
    { text: '机构匹配中…', status: TextStatus.UnActive },
  ]
  stepRun()
}
const visibilitychangeHandler = () => {
  if (!document.hidden) stepRun()
}

document.addEventListener('visibilitychange', visibilitychangeHandler);

onMounted(() => {
  if (route.query?.jumpUrl) {
    nextTick(() => {
      ProdJumpDialogRef.value?.show({
        url: route.query.jumpUrl as string
      })
    })
  } else {
    stepRun();
  }
  window.history.pushState({ waitPage: true }, 'waitPage', window.location.href);
  window.addEventListener('popstate', popstateHandler);
});

onUnmounted(() => {
  window.removeEventListener('popstate', popstateHandler);
  document.removeEventListener('visibilitychange', visibilitychangeHandler)
});
</script>

<style lang="scss" scoped>
/* 定义旋转动画 */
@keyframes continuous-rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.wait-page {
  background-color: #fff;
  // background-image: url(src/assets/images/waitpage/header.png);
  background-repeat: no-repeat;
  background-size: 100% auto;
  .wait-img{
    animation: continuous-rotate 2s linear infinite;

  }
  .body-img {
    width: 200px;
    height: 200px;
    position: relative;
    &-scan {
      animation: continuous-rotate 4s linear infinite;
      width: 200px;
      height: 200px;
    }
    &-dp{
      position: absolute;
      width: 90px;
      height: 84px;
      top: calc(50% - 42px);
      left: calc(50% - 45px);
    }
  }

  &-body {
    // background-image: url(src/assets/images/waitpage/bg.png);
    // background-repeat: no-repeat;
    // background-size: 100% auto;
    background-color: #fff;
    border-radius: 15px 15px 0;
    min-height: calc(100vh - 70px);
    // margin-top: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 29px;

  }

  &-detail {
    margin-top: 40px;

    .detail-item {
      display: flex;
      margin-bottom: 32px;
      align-items: center;
    }
  }

  &-text {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 32px;
    font-size: 18px;
    color: #333333;
    line-height: 25px;
  }

  &-tips {
    margin-top: 12px;
    font-size: 14px;
    color: #999999;
    line-height: 20px;
  }

  &-line {
    margin-top: 20px;
    width: 90vw;
    position: relative;

    .line-style {
      height: 8px;
      border-radius: 16px;

      position: absolute;
    }

    .line-block {
      position: absolute;
      width: 34px;
      height: 18px;
      background: #1277FF;
      border-radius: 16px;
      top: -6px;
      color: #fff;
      font-size: 10px;
      line-height: 14px;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.5s;
    }

    .un-active-line {
      background-color: #F4F6F9;
      width: 100%;
    }

    .active-line {
      background-color: #1277FF;
      transition: all 0.5s;
    }
  }
}
</style>
